<template>
  <Panel>
    <template #title>
      <p>添加账号</p>
    </template>
    <template #content>
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        size="mini"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="ruleForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pwd">
          <el-input
            type="password"
            v-model="ruleForm.pwd"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户组" prop="selectVal">
          <el-select v-model="ruleForm.selectVal" placeholder="请选择">
            <el-option
              v-for="item in userGroup"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')"
            >添加</el-button
          >
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </template>
  </Panel>
</template>

<script>
import { validateUserName, validatePWD } from '@/utils/validate.js'
import { addUser } from '@/api/users.js'

export default {
  data() {
    const select = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择用户角色'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {
        username: '',
        pwd: '',
        // 下拉框，需要最后选中的值，和一个默认遍历数据的值
        selectVal: ''
      },
      userGroup: [
        { value: '普通管理员', label: '普通管理员' },
        { value: '超级管理员', label: '超级管理员' }
      ],
      rules: {
        username: [{ validator: validateUserName, trigger: 'blur' }],
        pwd: [{ validator: validatePWD, trigger: 'blur' }],
        // selectVal: [{ required: true, message: '请选择角色', trigger: 'blur' }]
        selectVal: [{ validator: select, trigger: 'click' }]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const data = await addUser({
            account: this.ruleForm.username,
            password: this.ruleForm.pwd,
            userGroup: this.ruleForm.selectVal
          })
          // console.log(data)
          if (data.code === 0) {
            this.$router.push('/account/list')
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-form {
  width: 400px;

  /deep/ .el-input {
    width: 193px;
    input {
      width: 193px;
    }
  }
}
</style>
